package com.renshine.base.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.renshine.base.bean.Assemble;
import com.renshine.base.bean.Field;
import com.renshine.base.bean.Item;
import com.renshine.base.bean.Table;
import com.renshine.swing.component.dialog.CreateJDialog;
import com.renshine.swing.model.BaseTableModel;

/**
 * 数据的验证，获取,组装，生成
 * 
 * @author deyang
 *
 */
public class DataUtil {

	/**
	 * 取得选中的表
	 * 
	 * @param model 表格模型
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List<String> getSelectedTbNames(BaseTableModel model) {
		List<String> tbNames = new ArrayList<String>();
		Vector vector = model.getDataVector();
		Object[] objArray;
		if(vector != null && !vector.isEmpty()){
			for (Object object : vector) {
				objArray = ((Vector)object).toArray();
				tbNames.add(objArray[0].toString());
			}
		};
		return tbNames;
	}

	/**
	 * 数据组装
	 * 
	 * @param author
	 * @param module
	 * @param path
	 * @param template
	 * @param createJDialog
	 * @return
	 */
	public static Assemble assemble(String author, String module, String path,
			String template, CreateJDialog createJDialog) {
		Assemble assemble = new Assemble(author, module, template, path);
		List<Item> items = getItems(createJDialog);
		assemble.setItems(items);
		return assemble;
	}
	
	private static List<Item> getItems(CreateJDialog createJDialog) {
		List<Table> tbs = getSelectTables(createJDialog.getInitPanel().getModel());
		List<Item> items = new ArrayList<Item>();
		for (Table tb : tbs) {
			Item item = new Item();
			item.setTb(tb);
			item.setListEdit(getFields(createJDialog.getEditPanel().getMapModel().get(tb.getName())));
			item.setListSearch(getFields(createJDialog.getSearchPanel().getMapModel().get(tb.getName())));
			item.setListPage(getFields(createJDialog.getListPanel().getMapModel().get(tb.getName())));
			items.add(item);
		}
		return items;
	}
	
	@SuppressWarnings("rawtypes")
	private static List<Table> getSelectTables(BaseTableModel model) {
		List<Table> tbs = new ArrayList<Table>();
		Vector vector = model.getDataVector();
		Object[] objArray;
		if(vector != null && !vector.isEmpty()){
			for (Object object : vector) {
				objArray = ((Vector)object).toArray();
				tbs.add(new Table(objArray[0].toString(), objArray[1].toString(), objArray[2].toString()));
			}
		};
		return tbs;
	}

	@SuppressWarnings("rawtypes")
	private static List<Field> getFields(BaseTableModel model) {
		List<Field> listPage = new ArrayList<Field>();
		if (model == null) return listPage;
		Vector vector = model.getDataVector();
		Object[] objArray;
		if(vector != null && !vector.isEmpty()){
			Field field;
			for (Object object : vector) {
				objArray = ((Vector)object).toArray();
				field = new Field();
				field.setName(objArray[0].toString());
				field.setCondition(objArray[3].toString().trim());
				listPage.add(field);
			}
		};
		return listPage;
	}


}
